import React, { useRef, useState } from 'react';
import { useLocation, useNavigate } from 'react-router-dom';
import PageA from './PageA';
import PageB from './PageB';
import CircleTransition from './CircleTransition';
import { AnimatePresence } from 'framer-motion';

// 计算从(x, y)到视口四个角的最大距离，作为圆的最大半径，确保动画能覆盖全屏
const getMaxRadius = (x, y) => {
  const w = window.innerWidth;
  const h = window.innerHeight;
  const d1 = Math.hypot(x, y);
  const d2 = Math.hypot(w - x, y);
  const d3 = Math.hypot(x, h - y);
  const d4 = Math.hypot(w - x, h - y);
  return Math.max(d1, d2, d3, d4);
};

/**
 * 路由切换同心圆动画过渡组件
 * 只支持 /a 和 /b 两个路由页面的切换
 */
const RouterTransition = () => {
  const location = useLocation(); // 当前路由
  const navigate = useNavigate();
  const [animating, setAnimating] = useState(false); // 动画进行中
  const [pendingPath, setPendingPath] = useState(null); // 动画目标路由
  const [direction, setDirection] = useState('out'); // 动画方向
  const [center, setCenter] = useState({ x: 0, y: 0 }); // 动画圆心
  const [maxRadius, setMaxRadius] = useState(0); // 动画最大半径
  const [pendingSwitch, setPendingSwitch] = useState(false); // 动画完成后再切换路由
  const buttonRef = useRef(null);

  // 通过路由判断当前页面组件
  const getPageComponent = (path) => {
    if (path === '/routerTest/a') return <PageA />;
    if (path === '/routerTest/b') return <PageB />;
    return null;
  };

  // 点击按钮时，先启动动画，动画完成后再切换路由
  const handleRouteChange = (targetPath) => {
    if (buttonRef.current) {
      const rect = buttonRef.current.getBoundingClientRect();
      const x = rect.left + rect.width / 2;
      const y = rect.top + rect.height / 2;
      setCenter({ x, y });
      setMaxRadius(getMaxRadius(x, y));
      setPendingPath(targetPath);
      setDirection(targetPath === '/routerTest/b' ? 'out' : 'in');
      setAnimating(true);
      setPendingSwitch(false);
    }
  };

  // 动画完成时，先关闭动画层，等动画层unmount后再切换路由
  const handleAnimationComplete = () => {
    setAnimating(false);
    setPendingSwitch(true);
  };

  // 动画层完全unmount后再切换路由
  const handleExitComplete = () => {
    if (pendingSwitch && pendingPath) {
      navigate(pendingPath, { replace: true });
      setPendingPath(null);
      setPendingSwitch(false);
    }
  };

  // 动画期间，底层始终是当前页面，动画层始终是目标页面
  let basePage = getPageComponent(location.pathname);
  let transitionPage = pendingPath ? getPageComponent(pendingPath) : null;

  return (
    <div style={{ position: 'relative', width: '100vw', height: '100vh', overflow: 'hidden' }}>
      {/* 当前页面内容 */}
      {basePage}
      {/* 切换按钮，始终居中，动画时禁用 */}
      <button
        ref={buttonRef}
        onClick={() => handleRouteChange(location.pathname === '/routerTest/a' ? '/routerTest/b' : '/routerTest/a')}
        style={{
          position: 'absolute',
          left: '50%',
          top: '50%',
          transform: 'translate(-50%, -50%)',
          width: 80,
          height: 80,
          borderRadius: 16,
          background: '#1976d2',
          color: '#fff',
          fontSize: 24,
          border: 'none',
          cursor: 'pointer',
          zIndex: 10,
        }}
        disabled={animating || pendingSwitch}
      >
        切换
      </button>
      {/* 动画层，内容为目标页面 */}
      <AnimatePresence onExitComplete={handleExitComplete}>
        {animating && pendingPath && (
          <CircleTransition
            show={animating && !!pendingPath}
            center={center}
            maxRadius={maxRadius}
            direction={direction}
            onAnimationComplete={handleAnimationComplete}
          >
            {transitionPage}
          </CircleTransition>
        )}
      </AnimatePresence>
    </div>
  );
};

export default RouterTransition;
